import React, { useState, useEffect } from "react";
import { View, StyleSheet, Dimensions, Text, Image, TouchableOpacity } from "react-native";
import { useSelector, useDispatch } from "react-redux";
import IconNavBar from '@/components/IconNavBar'
import { sectokenCommonCenterProps } from '@/config/navigatorProps'
import { PayWithArray } from '@/config/config'
import { getETHSignData, getETHRejectData } from "@/utils/safe-transfer";
import Loading from "@/components/LoadingModal";
import { getValue } from "@/utils/deviceStorage";
import LockScreenEnter from '@/components/LockScreenEnter'
import CommonContext from '@/utils/createContext'

const { width, scale } = Dimensions.get('window')
const ratio = width * scale / 1080

const SectokenSendSelectOwner = (props) => {

    const dispatch = useDispatch()
    const selectedSafeWallet = useSelector((state) => state.sectokenMainReducer.selectedSafeWallet || {});
    const sendData = useSelector((state) => state.sectokenMainReducer.sendData || {});
    const transcationDetail = useSelector((state) => state.sectokenMainReducer.transcationDetail || {});
    const [loadingVisible, setLoadingVisible] = useState(false)
    const [ownerData, setOwnerData] = useState({});
    const [isRejection, setIsRejection] = useState(false);
    const [modalVisible, setModalVisible] = useState(false);

    useEffect(() => {
        let params = props.route.params
        if (params && params.source === 'rejection') {
            setIsRejection(true)
        }
    }, [props]);

    useEffect(() => {
        let obj = getValue('selectedWallet')
        let list = selectedSafeWallet.ownerList
        list && list.forEach(item => {
            if (item.address?.toLowerCase() === obj.address?.toLowerCase()) {
                setOwnerData(item)
            }
        });
    }, []);

    const handlePressLeft = () => {
        props.navigation.goBack()
    }

    const handlePressItem = () => {
        setModalVisible(true)
    }

    const handleClose = () => {
        setModalVisible(false)
        setLoadingVisible(true)
        setTimeout(async () => {
            let obj = {}
            let res
            if (isRejection) {
                //rejection
                res = await getETHRejectData(selectedSafeWallet, transcationDetail.detailedExecutionInfo?.nonce)
            } else {
                if (sendData && sendData.id) {
                    obj.address = sendData.address
                    obj.amount = (parseFloat(sendData.amount) * Math.pow(10, 18)).toString()
                } else {
                    obj.address = transcationDetail.txData?.to?.value
                    obj.amount = transcationDetail.txData?.value
                    obj.nonceData = {
                        currentNonce: transcationDetail.detailedExecutionInfo?.nonce,
                        safeTxGas: transcationDetail.detailedExecutionInfo?.safeTxGas?.toString(),
                    }
                }
                res = await getETHSignData(selectedSafeWallet, obj)
            }
            setLoadingVisible(false)
            if (res && res.txId) {
                dispatch({ type: "setSendData", value: {} });
                props.navigation.navigate({
                    name: 'safe-send-result',
                    params: {
                        source: 'send-owner',
                        txId: res.txId,
                        isRejection
                    }
                })
            }
        }, 100);
    }

    return (
        <View style={styles.container}>
            <IconNavBar {...props} {...sectokenCommonCenterProps} {...{ title: 'Select owner key' }} handlePressLeft={handlePressLeft} />
            <View style={styles.bodyContent}>
                <Text style={{ ...styles.title, textAlign: 'center', width: 273 * ratio }}>
                    An owner key will be used to confirm this transaction.
                </Text>
                {ownerData &&
                    <TouchableOpacity style={{ ...styles.content, marginTop: 24 * ratio }} onPress={handlePressItem}>
                        <Image style={styles.img}
                            source={PayWithArray[ownerData.profileImg]} />
                        <View style={{ marginLeft: 8 * ratio }}>
                            <Text style={styles.title}>{ownerData.label}</Text>
                            <Text style={{ ...styles.title, width: 94 * ratio }}
                                numberOfLines={1}
                                ellipsizeMode='middle'>
                                {ownerData.address}
                            </Text>
                        </View>
                    </TouchableOpacity>}
            </View>
            {modalVisible && <CommonContext.Provider value={{ modalVisible, setModalVisible, handleClose }}>
                <LockScreenEnter {...props} />
            </CommonContext.Provider>}
            {loadingVisible && <Loading visible={loadingVisible} />}
        </View>
    )
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#FFFFFF'
    },
    bodyContent: {
        flex: 1,
        marginTop: 11 * ratio,
        alignItems: 'center'
    },
    content: {
        width: 330 * ratio,
        height: 40 * ratio,
        flexDirection: 'row',
        alignItems: 'center'
    },
    img: {
        width: 40 * ratio,
        height: 40 * ratio
    },
    title: {
        fontSize: 14,
        fontFamily: 'SourceHanSansCN-Medium, SourceHanSansCN',
        fontWeight: '500',
        color: '#2C2C2C',
        lineHeight: 21
    }
})
export default SectokenSendSelectOwner